import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:getx_learn/app/common/widgets/widgets.dart';
import 'package:getx_learn/app/modules/weichat_post/modules/post/constant/config.dart';
import 'package:getx_learn/app/modules/weichat_post/util/bottom_sheet.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/appbar.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/camera/widgets/player.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/divider.dart';
import 'package:getx_learn/app/modules/weichat_post/widgets/gallery.dart';
import 'package:wechat_assets_picker/wechat_assets_picker.dart';

import '../controllers/post_controller.dart';

class PostEditPage extends GetView<PostController> {
  PostEditPage({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      // appBar: getAppBar(context: context, title: "PostView"),
      appBar: AppBarWidget(
        // 左侧返回
        leading: GestureDetector(
          onTap: () {
            Navigator.pop(context);
          },
          child: Icon(
            Icons.arrow_back_ios_new,
            color: Colors.black38,
          ),
        ),

        // 右侧发布
        actions: [
          Padding(
            padding: const EdgeInsets.only(right: pagePadding),
            child: ElevatedButton(
              onPressed: () {},
              // 样式风格
              style: ButtonStyle(
                // 设置按钮前景色
                foregroundColor: WidgetStateProperty.all(Colors.white),
                // 设置按钮背景色
                backgroundColor: WidgetStateProperty.all(Colors.green),
                // 设置按钮圆角
                shape: WidgetStateProperty.all(
                  RoundedRectangleBorder(
                    borderRadius: BorderRadius.all(
                      Radius.circular(6),
                    ),
                  ),
                ),
              ),
              child: Text(
                '发布',
              ),
            ),
          ),
        ],
      ),
      body: _mainView(context),
      bottomSheet: Obx(
        () {
          return controller.isDragNow.value
              ? _buildRemoveBar()
              : const SizedBox.shrink();
        },
      ),
    );
  }

  /// 内容输入框
  Widget _buildContentInput() {
    return Obx(() {
      final isContentEmpty = controller.contentText.isEmpty;
      return LimitedBox(
        maxHeight: 180,
        child: TextField(
          maxLines: null,
          maxLength: 20,
          keyboardType: TextInputType.none,
          controller: controller.contentController,
          decoration: InputDecoration(
            hintText: "这一刻的想法...",
            hintStyle: TextStyle(
              color: Colors.black12,
              fontSize: 18,
              fontWeight: FontWeight.w500,
            ),
            border: InputBorder.none,
            counterText: isContentEmpty ? "" : null,
          ),
          onChanged: (value) {
            controller.contentText.value = value;
          },
        ),
      );
    });
  }

  /// 菜单
  Widget _buildMenu() {
    List<Widget> ws = [];
    ws.add( DividerWidget());
    for (var menu in controller.menus) {
      ws.add(ListTile(
        leading: Icon(menu.icon),
        title: Text(menu.title!),
        trailing: Text(menu.right ?? ""),
        onTap: menu.onTab,
      ));
      ws.add( DividerWidget());
    }
    return Padding(
      padding: const EdgeInsets.only(top: 100.0),
      child: Column(
        children: ws,
      ),
    );
  }

  /// 主视图
  Widget _mainView(BuildContext context) {
    return SingleChildScrollView(
      child: Padding(
        padding: const EdgeInsets.all(pagePadding),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 内容输入
            _buildContentInput(),

            // 相册列表
            if (controller.postType == PostType.image) _buildPhotosList(context),

            Obx(() {
              // 视频播放器
              final asset = controller.selectedAssets.first;
              if (controller.postType == PostType.video)
                return VideoPlayerWidget(
                  initAsset: asset,
                  onComplete: (value) {},
                );
              return SizedBox.shrink();
            }),
            Obx(() {
              // 添加按钮
              final selectedAssets = controller.selectedAssets.value;
              if (controller.postType == null && selectedAssets.isEmpty)
                return Padding(
                  padding: EdgeInsets.all(spacing),
                  child: _buildAddBtn(context, 100),
                );

              return SizedBox.shrink();
            }),
            // 这里注释，将这里的内容放到 Scaffold(bottomSheet: 这里)
            // const Spacer(),
            // Obx(() {
            //   return controller.isDragNow.value
            //       ? _buildRemoveBar()
            //       : const SizedBox.shrink();
            // })

            _buildMenu(),
          ],
        ),
      ),
    );
  }

  /// 图片列表
  Widget _buildPhotosList(BuildContext context) {
    /// Warp 是自动换行的布局
    /// 使用 LayoutBuilder 进行动态计算宽高

    return LayoutBuilder(
        builder: (BuildContext context, BoxConstraints constraint) {
      final double width =
          (constraint.maxWidth - spacing * 4 - imagePadding * 2 * 3) / 3;
      return Padding(
        padding: const EdgeInsets.all(spacing),
        child: Obx(() {
          controller.selectedAssets;
          final isVideo = controller.selectedAssets.length == 1 &&
              controller.selectedAssets.first.type == AssetType.video;
          return Wrap(
            spacing: spacing,
            runSpacing: spacing,
            children: [
              if (!isVideo)
                for (final asset in controller.selectedAssets)
                  _buildPhotoItem(context, asset, width),

              // 加入按钮
              if (!isVideo)
                if (controller.selectedAssets.length < maxAssets)
                  _buildAddBtn(context, width),
            ],
          );
        }),
      );
    });

    // return Wrap(
    //   children: [
    //     for (final asset in controller.selectedAssets.value)
    //       AssetEntityImage(
    //         asset,
    //         width: 100,
    //         height: 100,
    //         fit: BoxFit.cover,
    //       ),
    //   ],
    // );
  }

  /// 构建图片视图
  /// @param context 上下文
  /// @param asset 选中的图片
  /// @param width 图片的宽度
  Widget _buildPhotoItem(
      BuildContext context, AssetEntity asset, double width) {
    /// 图片加入圆角
    final selectedAssets = controller.selectedAssets;
    return Draggable<AssetEntity>(
      // 此可拖动对象将拖放的数据
      data: asset,

      // 当可拖动对象开始被拖动时调用
      onDragStarted: () {
        controller.isDragNow.value = true;
      },

      // 当可拖动对象呗放下时调用
      onDragEnd: (detail) {
        controller.isDragNow.value = false;
      },

      // 当 draggable 被放置并被 [DragTarget] 接收时调用
      onDragCompleted: () {},

      // 被放置但未被 [DragTarget] 接受时调用
      onDraggableCanceled: (velocity, offset) {},

      // 图片被拖拽起来的时候，原本的位置的显示图片
      childWhenDragging: _buildPhotoItem1(asset, null, width, opacity: 0.5),

      // 拖动进行时显示在指针下发的小部件(就是跟随手指的图片)
      feedback: _buildPhotoItem1(asset, null, width),

      child: DragTarget<AssetEntity>(
        builder: (BuildContext context, List<AssetEntity?> candidateData,
            List<dynamic> rejectedData) {
          var targetId = "";
          if (candidateData.isNotEmpty) {
            targetId = candidateData[0]?.id.toString() ?? "";
          }
          print(
              "controller = ${controller.targetId} ${asset.id} ${candidateData}");
          return GestureDetector(
            onTap: () {
              // 方式 1 - 原生方式
              // Navigator.push(
              //   context,
              //   MaterialPageRoute(
              //     builder: (context) {
              //       return GalleryWidget(
              //           initialIndex: selectedAssets.indexOf(asset),
              //           items: selectedAssets);
              //     },
              //   ),
              // );

              // 方式2 - Get 的方式
              Get.to(
                GalleryWidget(
                    initialIndex: selectedAssets.indexOf(asset),
                    items: selectedAssets),
              );
            },
            child: _buildPhotoItem1(asset, targetId, width),
          );
        },
        onWillAcceptWithDetails: (data) {
          print("data = " + data.data.id);
          controller.targetId = data.data.id;
          controller.isWillOrder.value = true;
          return true;
        },
        onAcceptWithDetails: (data) {
          print("onAcceptWithDetails = " + data.data.id);
          final data1 = data.data;

          final selectedAssets = controller.selectedAssets;
          // 从队列中删除拖拽对象
          final int index = selectedAssets.indexOf(data1);
          selectedAssets.removeAt(index);
          // 将拖拽对象插入到目标对象之前
          final int targetIndex = selectedAssets.indexOf(asset);
          selectedAssets.insert(targetIndex, data1);

          controller.targetId = "";
          controller.isWillOrder.value = false;
        },
        onLeave: (data) {
          controller.targetId = "";
          controller.isWillOrder.value = false;
        },
      ),
    );
  }

  /// 构建图片 item（拖拽时候的指针也是用这个）
  /// @param asset 图片信息
  /// @param targetId 拖拽排序的时候，会传这个值
  /// @param width 图片的宽度和高度
  /// @param opacity 图片的透明度
  Widget _buildPhotoItem1(AssetEntity asset, String? targetId, double width,
      {double? opacity = null}) {
    return Container(
      // 图片被裁切，不加 Clip.antiAlias 看不到圆角
      clipBehavior: Clip.antiAlias,
      // 设置圆角装饰器，必须设置 clipBehavior: Clip.antiAlias, 否则不会有圆角
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(3),
        border:
            (controller.isWillOrder.value && controller.targetId == targetId)
                ? Border.all(
                    color: accentColor,
                    width: imagePadding,
                  )
                : Border.all(
                    color: Colors.transparent,
                    width: imagePadding,
                  ),
      ),
      child: AssetEntityImage(
        asset,
        width: width,
        height: width,
        fit: BoxFit.cover,
        opacity: opacity == null ? null : AlwaysStoppedAnimation(opacity),
      ),
    );
  }

  /// 构建图片添加按钮
  /// @param context 上下文
  /// @param width 图片宽度
  _buildAddBtn(BuildContext context, double width) {
    return GestureDetector(
      onTap: () async {
        // controller.selectPics(context);
        // controller.taskePhoto(context);

        final result = await DuBottomSheet(controller.selectedAssets)
            .wxPicker<List<AssetEntity>>(context);

        if (result == null || result.isEmpty) {
          return;
        }

        if (result.length == 1 && result.first.type == AssetType.video) {
          // 视频
          controller.postType = PostType.video;
        } else {
          // 图片
          controller.postType = PostType.image;
        }

        controller.selectedAssets.clear();
        controller.selectedAssets.addAll(result);
      },
      child: Container(
        width: width,
        height: width,
        decoration: BoxDecoration(
          color: Colors.black12,
          borderRadius: BorderRadius.circular(3),
          border: Border.all(
            color: Colors.transparent,
            width: imagePadding,
          ),
        ),
        child: Icon(
          Icons.add,
          size: 48,
          color: Colors.black38,
        ),
      ),
    );
  }

  // 删除 bar
  Widget _buildRemoveBar() {
    return DragTarget<AssetEntity>(
      // 调用构建小部件的内容
      builder: (BuildContext context, List<Object?> candidateData,
          List<dynamic> rejectedData) {
        return Container(
          height: 100,
          width: double.infinity,
          color:
              controller.isWillRemove.value ? Colors.red[300] : Colors.red[200],
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              // 图标
              Icon(
                Icons.delete,
                size: 32,
                color: controller.isWillRemove.value
                    ? Colors.white
                    : Colors.white70,
              ),
              // 文字
              Text(
                "拖拽到这里删除",
                style: TextStyle(
                    color: controller.isWillRemove.value
                        ? Colors.white
                        : Colors.white70),
              ),
            ],
          ),
        );
      },

      // 调用以确定此小部件是否有兴趣接收给定的 被拖动到这个拖动目标上的数据片段。
      onWillAcceptWithDetails: (details) {
        controller.isWillRemove.value = true;
        // 这里返回 true，才会执行 onAcceptWithDetails，如果返回 false 则不会执行
        return true;
      },

      // 当一条可接受的数据被拖放到这个拖动目标上时调用。
      // onWillAcceptWithDetails 返回 true，才会执行当前方法
      onAcceptWithDetails: (data) {
        var selectedAssets = controller.selectedAssets;
        selectedAssets.remove(data.data);
        controller.isWillRemove.value = false;
      },

      // 当被拖动到该目标上的给定数据离开时调用 目标。
      onLeave: (data) {
        controller.isWillRemove.value = false;
      },
    );
  }
}
